package com.demo.system.init.sentinel.handle;

import com.alibaba.csp.sentinel.adapter.servlet.callback.UrlBlockHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author ：qilong sun
 * @date ：Created in 2020/8/13 14:59
 * @description：web端block事件
 * @modified By：
 * @version: V1.0$
 */
@Slf4j
public class CustomerUrlBlockHandler implements UrlBlockHandler {
    @Override
    public void blocked(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, BlockException e) throws IOException {
        Map<String, Object> map = new HashMap<>();
        map.put("code", 400);
        if (e instanceof FlowException) {
            map.put("msg", "限流了");
        } else if (e instanceof DegradeException) {
            map.put("msg", "降级了");
        }
        log.error("这里是CustomerUrlBlockHandler，我被" + map.get("msg"));
        httpServletResponse.setContentType(MediaType.APPLICATION_JSON_VALUE);
        httpServletResponse.getWriter().write(JSONObject.toJSONString(map));
    }
}
